<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="id" label="" required>
        <uni-easyinput placeholder="业务ID（前端生成）" v-model="formData.id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="waterPlantName" label="" required>
        <uni-easyinput placeholder="水厂名称（站点名称）" v-model="formData.waterPlantName"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="plantId" label="">
        <uni-easyinput placeholder="水厂站点ID（与sites表关联）" v-model="formData.plantId"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="createDate" label="" required>
        <uni-easyinput placeholder="创建日期，格式：YYYY-MM-DD" v-model="formData.createDate"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="" required>
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="completionTime" label="">
        <uni-easyinput placeholder="完成时间，格式：YYYY-MM-DD HH:mm（可选）" v-model="formData.completionTime"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="type" label="" required>
        <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="title" label="" required>
        <uni-easyinput placeholder="问题标题" v-model="formData.title"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="">
        <uni-easyinput placeholder="问题描述" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="severity" label="" required>
        <uni-data-checkbox v-model="formData.severity" :localdata="formOptions.severity_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="deadline" label="" required>
        <uni-easyinput placeholder="建议完成期限，格式：YYYY-MM-DD" v-model="formData.deadline"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="images" label="">
        <uni-data-checkbox :multiple="true" v-model="formData.images"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="videos" label="">
        <uni-data-checkbox :multiple="true" v-model="formData.videos"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="rectificationNote" label="">
        <uni-easyinput placeholder="整改说明（可选）" v-model="formData.rectificationNote"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="rectificationMedia" label="">
        <uni-data-checkbox :multiple="true" v-model="formData.rectificationMedia"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="deviceName" label="">
        <uni-easyinput placeholder="设备名称（可选）" v-model="formData.deviceName"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/zhenggaidan.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'zhenggaidan';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "id": "",
        "waterPlantName": "",
        "plantId": "",
        "createDate": "",
        "status": "",
        "completionTime": "",
        "type": "",
        "title": "",
        "description": "",
        "severity": "",
        "deadline": "",
        "images": [],
        "videos": [],
        "rectificationNote": "",
        "rectificationMedia": [],
        "deviceName": ""
      }
      return {
        formData,
        formOptions: {
          "status_localdata": [
            {
              "value": "待整改",
              "text": "待整改"
            },
            {
              "value": "已整改",
              "text": "已整改"
            }
          ],
          "type_localdata": [
            {
              "value": "设备",
              "text": "设备"
            },
            {
              "value": "卫生",
              "text": "卫生"
            },
            {
              "value": "安全",
              "text": "安全"
            },
            {
              "value": "其他",
              "text": "其他"
            }
          ],
          "severity_localdata": [
            {
              "value": "严重",
              "text": "严重"
            },
            {
              "value": "一般",
              "text": "一般"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("id,waterPlantName,plantId,createDate,status,completionTime,type,title,description,severity,deadline,images,videos,rectificationNote,rectificationMedia,deviceName").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
